package com.offcn.filter;

import com.offcn.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
//登录过滤器
@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //向下转型
        HttpServletRequest req = (HttpServletRequest)servletRequest;
        HttpServletResponse resp = (HttpServletResponse)servletResponse;
        //获取uri地址
        String uri = req.getRequestURI();
        //截取出需要的地址
        String uriPath = uri.substring(uri.lastIndexOf("/")+1);
        //判断，所有登录之前的操作直接放行，否则查看是否有用户信息，有就直接放行，没有就回到登录页面去登录
        if("register.jsp".equals(uriPath)||"register".equals(uriPath)||"hello".equals(uriPath)||"index.jsp".equals(uriPath)){
            filterChain.doFilter(req,resp);
        }else {
            HttpSession session = req.getSession();
            Object user = (User)session.getAttribute("user");
            if(user!=null){
                filterChain.doFilter(req,resp);
            }else{
                resp.sendRedirect("index.jsp");
            }
        }
    }
}
